package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author Dugen.Zhu
 * @date 2020-01-06 21:24
 */
@Component
public class SpringSecurityUserService implements UserDetailsService {

    //使用dubbo远程调用使用数据库查询
    @Reference
    private UserService userService;

    //根据用户名查询数据库获取用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User myUser = userService.findByUsername(username);
        if (myUser == null) {
            //如果user为空，那么返回null交给SpringSecurity处理
            return null;
        }
        //创建权限列表
        List<GrantedAuthority> list = new ArrayList<>();
        //获取user的角色
        Set<Role> roles = myUser.getRoles();
        for (Role role : roles) {
            //授予用户分配的角色
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                //授予角色分配的权限
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        //返回user对象交给SpringSecurity处理
        org.springframework.security.core.userdetails.User user = new org.springframework.security.core.userdetails.User(username, myUser.getPassword(), list);
        return user;
    }
}
